package com.css.fxfzypg.modules.rating.task.service;

import cn.hutool.core.util.IdUtil;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.rating.task.dao.KpRatingTaskProgressRepository;
import com.css.fxfzypg.modules.rating.task.dao.KpRatingTaskRepository;
import com.css.fxfzypg.modules.rating.task.model.dto.ApplyYpgTaskDto;
import com.css.fxfzypg.modules.rating.task.model.dto.NewKpTaskDto;
import com.css.fxfzypg.modules.rating.task.model.dto.NewTaskYpgTaskDto;
import com.css.fxfzypg.modules.rating.task.model.entity.KpRatingTask;
import com.css.fxfzypg.modules.rating.task.model.entity.KpRatingTaskProgress;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 新建考评任务
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class KpRatingTaskNewService {
    @Autowired
    KpRatingTaskService kpRatingTaskService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    KpRatingTaskRepository kpRatingTaskRepository;
    @Autowired
    KpRatingTaskProgressRepository kpRatingTaskProgressRepository;

    /**
     * 获取用户上次未保存的任务
     *
     * @param currUid
     * @return
     */
    public NewKpTaskDto getLatestUnsaveTask(String currUid) {
        return kpRatingTaskService.getLatestUnsaveKpTaskFromCache(currUid);
    }

    /**
     * 应用关联任务
     *
     * @param dto
     * @param currUid : 用户id
     */
    public void applyGlTask(ApplyYpgTaskDto dto, String currUid) {
        NewKpTaskDto latestCreateKpTaskFromCache = kpRatingTaskService.getLatestUnsaveKpTaskFromCache(currUid);
        // 1.设置任务信息
        latestCreateKpTaskFromCache.setName(dto.getTaskName());
        latestCreateKpTaskFromCache.setKesdId(dto.getKesdId());
        latestCreateKpTaskFromCache.setExpertGroupId(dto.getExpertGroupId());
        latestCreateKpTaskFromCache.setEndDate(dto.getEndDate());
        // 2.添加关联任务
        List<NewTaskYpgTaskDto> taskList = latestCreateKpTaskFromCache.getTaskList();
        if (taskList == null) {
            taskList = new ArrayList<>();
        }
        if (dto.getList() == null) {
            return;
        }
        for (ApplyYpgTaskDto.Task task : dto.getList()) {
            if (StringUtils.isBlank(task.getId())) {
                // 2.1 没传id则新建
                prepareInsertGlTaskToCache(task, taskList);
            } else {
                // 2.2 传id则覆盖
                prepareUpdateGlTaskToCache(task, taskList);
            }
        }
        latestCreateKpTaskFromCache.setTaskList(taskList);
        kpRatingTaskService.saveLatestUnsaveTaskToCache(currUid, latestCreateKpTaskFromCache);
    }

    private void prepareInsertGlTaskToCache(ApplyYpgTaskDto.Task dto, List<NewTaskYpgTaskDto> taskList) {
        NewTaskYpgTaskDto newTaskYpgTaskDto = new NewTaskYpgTaskDto();
        newTaskYpgTaskDto.setId(IdUtil.simpleUUID());
        newTaskYpgTaskDto.setYpgId(dto.getYpgId());
        newTaskYpgTaskDto.setXcdcId(dto.getXcdcId());
        newTaskYpgTaskDto.setProvinceIdList(dto.getProvinceIdList());
        newTaskYpgTaskDto.setJbReportId(dto.getJbReportId());
        newTaskYpgTaskDto.setXbReportId(dto.getXbReportId());
        newTaskYpgTaskDto.setXcdcReportId(dto.getXcdcReportId());
        newTaskYpgTaskDto.setCreateTime(new Date());
        dto.setId(newTaskYpgTaskDto.getId());
        taskList.add(newTaskYpgTaskDto);
    }

    private void prepareUpdateGlTaskToCache(ApplyYpgTaskDto.Task dto, List<NewTaskYpgTaskDto> taskList) {
        if (taskList.size() == 0) {
            prepareInsertGlTaskToCache(dto, taskList);
            return;
        }
        taskList.forEach(o -> {
            if (o.getId().equals(dto.getId())) {
                o.setYpgId(dto.getYpgId());
                o.setXcdcId(dto.getXcdcId());
                o.setProvinceIdList(dto.getProvinceIdList());
                o.setJbReportId(dto.getJbReportId());
                o.setXbReportId(dto.getXbReportId());
                o.setXcdcReportId(dto.getXcdcReportId());
            }
        });
    }

    /**
     * 删除关联任务
     *
     * @param id
     * @param currUid
     */
    public void deleteGlTask(String id, String currUid) {
        NewKpTaskDto latestCreateKpTaskFromCache = kpRatingTaskService.getLatestUnsaveKpTaskFromCache(currUid);
        List<NewTaskYpgTaskDto> taskList = latestCreateKpTaskFromCache.getTaskList();
        taskList.removeIf(newTaskYpgTaskDto -> newTaskYpgTaskDto.getId().equals(id));
        kpRatingTaskService.saveLatestUnsaveTaskToCache(currUid, latestCreateKpTaskFromCache);
    }

    public void cleanKpTask(String currUid) {
        kpRatingTaskService.cleanLatestUnsaveTaskToCache(currUid);
    }

//    @Transactional(rollbackFor = Exception.class)
//    public void newKpTaskSaveKpTask(NewKpTaskDto dto, String currUid) {
//        Date currTime = new Date();
//        // 保存考评任务信息
//        KpRatingTask kpRatingTask = insertKpTask(dto, currUid, currTime);
//        // 保存关联任务
//        kpRatingTaskService.insertGlTask(dto, currUid, kpRatingTask);
//        // 保存进程信息
//        insertProgress(currTime, kpRatingTask, 0);
//        // 清除缓存
//        cleanLatestUnsaveKpTaskCache(currUid);
//    }

    /**
     * 保存考评任务
     *
     * @param currUid 保存人
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveKpTask(String currUid) {
        Date currTime = new Date();
        NewKpTaskDto latestKpTask = kpRatingTaskService.getLatestUnsaveKpTaskFromCache(currUid);
        // 保存考评任务信息
        KpRatingTask kpRatingTask = insertKpTask(latestKpTask, currUid, currTime);
        // 保存关联任务
        kpRatingTaskService.insertGlTask4Update(latestKpTask, currUid, kpRatingTask);
        // 保存进程信息
        insertProgress(currTime, kpRatingTask.getId(), 0);
        // 清除缓存
        cleanLatestUnsaveKpTaskCache(currUid);
    }

    /**
     * 清除未保存考评任务缓存
     *
     * @param currUid
     */
    private void cleanLatestUnsaveKpTaskCache(String currUid) {
        HashOperations<String, String, NewKpTaskDto> hashOps = redisTemplate.opsForHash();
        hashOps.delete(KpRatingTaskService.CURR_USER_LATEST_CREATING_KP_TASK, currUid);
    }

    /**
     * 保存考评任务
     *
     * @param dto
     * @param currUid
     * @param currTime
     * @return
     */
    private KpRatingTask insertKpTask(NewKpTaskDto dto, String currUid, Date currTime) {
        KpRatingTask kpRatingTask = new KpRatingTask();
        kpRatingTask.setId(IdUtil.simpleUUID());
        kpRatingTask.setName(dto.getName());
        kpRatingTask.setKesdId(dto.getKesdId());
        kpRatingTask.setExpertGroupId(dto.getExpertGroupId());
        kpRatingTask.setEndDate(dto.getEndDate());
        kpRatingTask.setCreateTime(currTime);
        kpRatingTask.setCreateUser(currUid);
        kpRatingTask.setUpdateTime(currTime);
        kpRatingTask.setUpdateUser(currUid);
        kpRatingTask.setDelFlag(YNEnum.N.toString());
        kpRatingTask.setIsRunAreaRatio(0);
        kpRatingTaskRepository.insert(kpRatingTask);
        return kpRatingTask;
    }

    /**
     * 保存考评任务进度信息
     *
     * @param currTime
     * @param krtId
     */
    private void insertProgress(Date currTime, String krtId, int status) {
        KpRatingTaskProgress kpRatingTaskProgress = kpRatingTaskProgressRepository.getByKrtIdAndStatus(krtId, status);
        if (kpRatingTaskProgress == null) {
            kpRatingTaskProgress = new KpRatingTaskProgress();
            kpRatingTaskProgress.setId(IdUtil.simpleUUID());
            kpRatingTaskProgress.setStatus(status);
            kpRatingTaskProgress.setStatusTime(currTime);
            kpRatingTaskProgress.setKrtId(krtId);
            kpRatingTaskProgressRepository.insert(kpRatingTaskProgress);
        }
    }
}
